package ec.fugu.util;

import java.util.Vector;

public class TaskWorker implements Runnable {
    private boolean quit = false;
    private Vector queue = new Vector();

    public TaskWorker() {
        new Thread(this).start();
    }

    private Task getNext() {
    	Task task = null;
        if (!queue.isEmpty()) {
            task = (Task) queue.firstElement();
        }
        return task;
    }

    public void run() {
        while (!quit) {
        	Task task = getNext();
            if (task != null) {
                System.out.println("Iniciando task: " + task.toString());
                task.doTask();
                queue.removeElement(task);
                System.err.println("Terminada task: " + task.toString());
            } else {// task is null and only reason will be that vector has no more tasks
                synchronized (queue) {
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

     public void addTask(Task task) {
        synchronized (queue) {
            if (!quit) {
                queue.addElement(task);
                queue.notify();

            }

        }
    }

    public void quit() {
        synchronized (queue) {
            quit = true;
            queue.notify();
        }
    }
}